package com.yungee.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static final int CONNECT_DEFAULT_TIME_OUT = 5000;
    private static final int CONNECT_REQUEST_DEFAULT_TIME_OUT = 5000;
    private static final int SOCKET_DEFAULT_TIME_OUT = 5000;
    private static final int MAX_TOTAL_CONNECTIONS = 200;
    private static final int MAX_ROUTE_CONNECTIONS = 200;
    private static CloseableHttpClient client;
    private static final String JSON_ERRNO = "error_code";
    private static final String JSON_ERRMSG = "error_msg";

    public HttpUtil() {
    }

    public static HttpResult getByTimeout(String url, Map<String, String> headers, Map<String, String> params, int connectTimeout, int connectRequestTimeout, int socketTimeout) throws ClientProtocolException, IOException {
        return get(url, headers, params, connectTimeout, connectRequestTimeout, socketTimeout);
    }

    public static HttpResult get(String url, Map<String, String> headers, Map<String, String> params) throws ClientProtocolException, IOException {
        return get(url, headers, params, 5000, 5000, 5000);
    }

    public static HttpResult post(String url, Map<String, String> headers, Map<String, String> params, String encoding) throws ClientProtocolException, IOException {
        return post(url, headers, params, encoding, 5000, 5000, 5000);
    }

    public static HttpResult delete(String url, Map<String, String> headers, Map<String, String> params) throws ClientProtocolException, IOException {
        return delete(url, headers, params, 5000, 5000, 5000);
    }

    public static HttpResult delete(String url, Map<String, String> headers, Map<String, String> params, int connectTimeout, int connectRequestTimeout, int scoketTimeout) throws ClientProtocolException, IOException {
        URI uri = null;

        Iterator var8;
        Map.Entry entry;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            var8 = params.entrySet().iterator();

            while(true) {
                if (!var8.hasNext()) {
                    uri = uriBuilder.build();
                    break;
                }

                entry = (Map.Entry)var8.next();
                uriBuilder.addParameter((String)entry.getKey(), (String)entry.getValue());
            }
        } catch (URISyntaxException var33) {
            log.error(var33.getMessage(), var33);
            return null;
        }

        RequestBuilder builder = RequestBuilder.delete().setUri(uri).setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectRequestTimeout).setSocketTimeout(scoketTimeout).build());
        var8 = headers.entrySet().iterator();

        while(var8.hasNext()) {
            entry = (Map.Entry)var8.next();
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        }

        HttpUriRequest request = builder.build();
        CloseableHttpResponse response = client.execute(request);
        Throwable var10 = null;

        HttpResult var13;
        try {
            HttpEntity entity = null;

            try {
                entity = response.getEntity();
                HttpResult result = new HttpResult();
                result.setStatusCode(response.getStatusLine().getStatusCode());
                result.setHeaders(response.getAllHeaders());
                result.setHttpEntity(entity);
                result.setBody(EntityUtils.toString(entity));
                var13 = result;
            } finally {
                EntityUtils.consumeQuietly(entity);
            }
        } catch (Throwable var31) {
            var10 = var31;
            throw var31;
        } finally {
            if (response != null) {
                if (var10 != null) {
                    try {
                        response.close();
                    } catch (Throwable var29) {
                        var10.addSuppressed(var29);
                    }
                } else {
                    response.close();
                }
            }

        }

        return var13;
    }

    public static HttpResult get(String url, Map<String, String> headers, Map<String, String> params, int connectTimeout, int connectRequestTimeout, int scoketTimeout) throws ClientProtocolException, IOException {
        URI uri = null;

        Iterator var8;
        Map.Entry entry;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            var8 = params.entrySet().iterator();

            while(true) {
                if (!var8.hasNext()) {
                    uri = uriBuilder.build();
                    break;
                }

                entry = (Map.Entry)var8.next();
                uriBuilder.addParameter((String)entry.getKey(), (String)entry.getValue());
            }
        } catch (URISyntaxException var33) {
            log.error(var33.getMessage(), var33);
            return null;
        }

        RequestBuilder builder = RequestBuilder.get().setUri(uri).setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectRequestTimeout).setSocketTimeout(scoketTimeout).build());
        var8 = headers.entrySet().iterator();

        while(var8.hasNext()) {
            entry = (Map.Entry)var8.next();
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        }

        HttpUriRequest request = builder.build();
        CloseableHttpResponse response = client.execute(request);
        Throwable var10 = null;

        HttpResult var13;
        try {
            HttpEntity entity = null;

            try {
                entity = response.getEntity();
                HttpResult result = new HttpResult();
                result.setStatusCode(response.getStatusLine().getStatusCode());
                result.setHeaders(response.getAllHeaders());
                result.setHttpEntity(entity);
                result.setBody(EntityUtils.toString(entity));
                var13 = result;
            } finally {
                EntityUtils.consumeQuietly(entity);
            }
        } catch (Throwable var31) {
            var10 = var31;
            throw var31;
        } finally {
            if (response != null) {
                if (var10 != null) {
                    try {
                        response.close();
                    } catch (Throwable var29) {
                        var10.addSuppressed(var29);
                    }
                } else {
                    response.close();
                }
            }

        }

        return var13;
    }

    public static HttpResult post(String url, Map<String, String> headers, Map<String, String> params, String encoding, int connectTimeout, int connectRequestTimeout, int scoketTimeout) throws ClientProtocolException, IOException {
        URI uri = null;

        try {
            uri = (new URIBuilder(url)).build();
        } catch (URISyntaxException var36) {
            log.error(var36.getMessage(), var36);
            return null;
        }

        HttpEntity requestEntity = null;
        List<NameValuePair> bodyParams = Lists.newLinkedList();
        Iterator var10 = params.entrySet().iterator();

        while(var10.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var10.next();
            bodyParams.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
        }

        ContentType contentType = ContentType.create(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), encoding);
        requestEntity = EntityBuilder.create().setContentType(contentType).setParameters(bodyParams).build();
        RequestBuilder builder = RequestBuilder.post().setUri(uri).setEntity(requestEntity).setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectRequestTimeout).setSocketTimeout(scoketTimeout).build());
        Iterator var12 = headers.entrySet().iterator();

        while(var12.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var12.next();
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        }

        HttpUriRequest request = builder.build();
        CloseableHttpResponse response = client.execute(request);
        Throwable var14 = null;

        HttpResult var17;
        try {
            HttpEntity responseEntity = null;

            try {
                responseEntity = response.getEntity();
                HttpResult result = new HttpResult();
                result.setStatusCode(response.getStatusLine().getStatusCode());
                result.setHeaders(response.getAllHeaders());
                result.setHttpEntity(requestEntity);
                result.setBody(EntityUtils.toString(responseEntity));
                var17 = result;
            } finally {
                EntityUtils.consumeQuietly(responseEntity);
            }
        } catch (Throwable var35) {
            var14 = var35;
            throw var35;
        } finally {
            if (response != null) {
                if (var14 != null) {
                    try {
                        response.close();
                    } catch (Throwable var33) {
                        var14.addSuppressed(var33);
                    }
                } else {
                    response.close();
                }
            }

        }

        return var17;
    }

    public static HttpResult jsonPost(String url, Map<String, String> headers, Map<String, Object> params, int connectTimeout, int connectRequestTimeout, int socketTimeout) throws IOException {
        URI uri;
        try {
            uri = (new URIBuilder(url)).build();
        } catch (URISyntaxException var34) {
            log.error(var34.getMessage(), var34);
            return null;
        }

        JSONObject obj = new JSONObject();
        if (params != null) {
            Iterator var8 = params.entrySet().iterator();

            while(var8.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)var8.next();
                obj.put((String)entry.getKey(), entry.getValue());
            }
        }

        StringEntity se = new StringEntity(obj.toJSONString(), StandardCharsets.UTF_8);
        se.setContentEncoding("UTF-8");
        se.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        RequestBuilder builder = RequestBuilder.post().setUri(uri).setEntity(se).setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectRequestTimeout).setSocketTimeout(socketTimeout).build());
        Iterator var10 = headers.entrySet().iterator();

        while(var10.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var10.next();
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        }

        HttpUriRequest request = builder.build();
        CloseableHttpResponse response = client.execute(request);
        Throwable var12 = null;

        HttpResult var15;
        try {
            HttpEntity responseEntity = null;

            try {
                responseEntity = response.getEntity();
                HttpResult result = new HttpResult();
                result.setStatusCode(response.getStatusLine().getStatusCode());
                result.setHeaders(response.getAllHeaders());
                result.setHttpEntity(se);
                result.setBody(EntityUtils.toString(responseEntity));
                var15 = result;
            } finally {
                EntityUtils.consumeQuietly(responseEntity);
            }
        } catch (Throwable var33) {
            var12 = var33;
            throw var33;
        } finally {
            if (response != null) {
                if (var12 != null) {
                    try {
                        response.close();
                    } catch (Throwable var31) {
                        var12.addSuppressed(var31);
                    }
                } else {
                    response.close();
                }
            }

        }

        return var15;
    }

    public static HttpResult jsonPost(String url, Map<String, String> headers, Map<String, Object> params) throws IOException {
        return jsonPost(url, headers, params, 5000, 5000, 5000);
    }

    private static Header[] parseHeader(Map<String, String> headers) {
        if (null != headers && !headers.isEmpty()) {
            Header[] allHeader = new BasicHeader[headers.size()];
            int i = 0;

            for(Iterator var3 = headers.keySet().iterator(); var3.hasNext(); ++i) {
                String str = (String)var3.next();
                allHeader[i] = new BasicHeader(str, (String)headers.get(str));
            }

            return allHeader;
        } else {
            return getDefaultHeaders();
        }
    }

    public static HttpResult uploadFile(String url, File file, Map<String, String> headers, Map<String, String> params, String encoding) throws ClientProtocolException, IOException {
        HttpPost post = new HttpPost(url);
        FileBody fileBody = new FileBody(file);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("rawImgFile", fileBody);
        Iterator var8 = params.keySet().iterator();

        while(var8.hasNext()) {
            String paramName = (String)var8.next();
            StringBody paramValue = new StringBody((String)params.get(paramName), ContentType.TEXT_PLAIN);
            multipartEntityBuilder.addPart(paramName, paramValue);
        }

        HttpEntity reqEntity = multipartEntityBuilder.build();
        post.setEntity(reqEntity);
        post.setHeaders(parseHeader(headers));
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        HttpResult result = new HttpResult();
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    private static Header[] getDefaultHeaders() {
        Header[] allHeader = new BasicHeader[]{new BasicHeader("Content-Type", "application/x-www-form-urlencoded"), new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36")};
        return allHeader;
    }

    public static void closeClient(CloseableHttpClient client) {
        if (null != client) {
            try {
                client.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }
        }

    }

    public static String getRemoteIp(HttpServletRequest request) {
        if (request == null) {
            return null;
        } else {
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }

            return ip;
        }
    }

    static {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).build();
        client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).setMaxConnTotal(200).setMaxConnPerRoute(200).build();
    }
}
